<template>
  <view :style="{ opacity: curPage === 'map' ? '0' : '1'}">
    <uni-nav-bar title="新增车友团" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
    <view class="package space-between">
      <view>车友团别名</view>
      <input class="uni-input" placeholder="请输入团名" v-model="name" />
    </view>
    <view class="package">
      <view>团助理</view>
      <view class="center image" style="flex-wrap: wrap;">
        <view :class="admin_id==item.id?'active':''" v-for="item in AssistantList" :key='item.id'
          @click="()=>admin_id=item.id">{{item.name}}</view>
      </view>
      <view class="space-between top">
        <view>团状态</view>
        <uni-data-checkbox v-model="state1" :localdata="type1" @change="changes($event,'state1')"></uni-data-checkbox>
      </view>
      <view class="space-between top">
        <view>团类型</view>
        <uni-data-checkbox v-model="state2" :localdata="type2"></uni-data-checkbox>
      </view>
      <view class="space-between top" @click="chooseLocation">
        <view>位置</view>
        <view style="width:70%;">{{locName}}</view>
      </view>
    </view>
  </view>
  <view class="package space-between" v-if="state2!=1">
    <view>是否验证资格</view>
    <uni-icons type="circle-filled" size="20" :color="!is_check?'#999':'#1F92FE'"
      @click="()=>is_check=!is_check"></uni-icons>
  </view>
  <view class="package" v-if="state2!=1">
    <view class="space-between">
      <view class="center">
        <uni-icons type="circle-filled" size="20" color="#1F92FE"></uni-icons>
        <view style="margin-left: 10rpx;">郑州</view>
      </view>
      <view class="center price">
        <view>微信</view>
        <view style="margin:0px 10rpx;" @click="increase('wechat')">{{price[0].wechat}}</view>
        <view>余额</view>
        <view style="margin-left: 10rpx;" @click="increase('money')">{{price[0].money}}</view>
      </view>
    </view>
  </view>
  <!-- navTo('administrator/teamList/teamList') -->
  <view class="add" @click="SureTeam()">确定</view>
  <view style="width: 100%;height:1px;"></view>
  <!-- 选择地址列表 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
  <!-- 填写价 -->
  <Price @submit="submit" ref="AddPrice"></Price>
</template>

<script setup lang="ts">
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  import { navBack, navTo } from '@/utils/navigator';
  import Price from '@c/administrator/BulletBox/payFor.vue';
  import Lotlats from '@c/team/Lotlat.vue';
  import { Assistant } from '@/gql/team';
  import { showLoading, errorToast } from '@/utils/prompt';
  import { toPublish } from '@mqtt';
  import { ref, Ref } from 'vue';
  /**
   * 新增车友团
   * @property {Null} AddPrice 填写价弹框
   * @property {Number} state1 团状态
   * @property {Array} type1 团状态数组
   * @property {Number} state2 团类型
   * @property {Array} type2 团类型数组
   * @property {Boolean} is_check 是否开启双向验证
   * @property {String} name 团名
   * @property {Array} price 价格区域
   * @property {String} payType 修改的价格类型
   * @property {String} admin_id 团助理ID
   * @property {Array} AssistantList 团助理列表
   * @property {String} curPage 选择位置页面
   * @property {Number} longitude 当前位置的经度
   * @property {Number} latitude 当前位置的纬度
   * @property {String} mapURI 跳转地图页面
   * @property {String} locName 选择当前位置信息
   */
  const AddPrice = ref(null)
  const state1 = ref(0) //是否成团
  const type1 = [{ text: '未成团', value: 0 }, { text: '已成团', value: 1 }]
  const state2 = ref(1) //团类型
  const type2 = [{ text: '普通团', value: 1 }, { text: '超级团', value: 2 }]
  const is_check = ref(false) //是否验证资格
  const name = ref('')//团名
  const price = ref([{ code: "0371", money: '0.00', wechat: '0.00' }])
  const payType = ref('')
  const admin_id = ref(''); //助理ID
  const AssistantList = ref([]); //团助理列表
  // data
  const curPage : Ref<'form' | 'map'> = ref('form');
  const longitude = ref()
  const latitude = ref()
  const mapURI = ref('');
  const locName = ref('')
  /**
   * 获取助理列表
   */
  Assistants();
  function Assistants() {
    showLoading('正在加载');
    const payload = {
      query: Assistant,
    };
    toPublish('ql/team/getAdmin', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      AssistantList.value = data.admin_list;
      admin_id.value = data.admin_list.length > 0 ? data.admin_list[0].id : ''
    });
  }
  function increase(num : string) {
    payType.value = num
    AddPrice.value.openBankPad()
  }
  // 填写价
  function submit(num : number) {
    console.log(num)
    switch (payType.value) {
      case 'wechat':
        price.value[0].wechat = num
        break;
      case 'money':
        price.value[0].money = num
        break;
    }
  }
  /**
   * 获取当前城市信息
   * @param  lat 当前位置的纬度
   * @param  lot 当前位置的经度
   * @return MapPage 修改地图页面的first状态
   */
  function position(lat : number, lot : number) {
    longitude.value = lot;
    latitude.value = lat;
    getPositionByLonLats(lot, lat)
  }
  function getPositionByLonLats(lng : number, lat : number) {
    AMapLoader.load({
      key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
    })
      .then(AMap => {
        const lnglat = [lng, lat]
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, function (status : any, result : any) {
          if (status === 'complete' && result.regeocode) {
            locName.value = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
      })
  }
  /**
   * 跳转到地址列表 选择位置信息
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        console.log(JSON.stringify(loc) + '*****')
        curPage.value = 'form';
        longitude.value = loc.latlng.lng;
        latitude.value = loc.latlng.lat;
        locName.value = loc.poiname
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  /**
   * 提交成团
   * @property {Number} longitude 当前位置的经度
   * @property {Number} latitude 当前位置的纬度
   * @property {Boolean} is_check 是否开启双向验证
   * @property {Number} status 团状态
   * @property {Number} type 团类型
   * @property {String} address 选择当前位置信息
   * @property {Array} price 价格区域
   * @property {String} name 团名
   * @property {String} admin_id 团助理ID
   */
  function SureTeam() {
    if (!name.value) {
      errorToast('请输入团名称')
      return
    }
    if (state2.value === 2 && price.value[0].money == '0.00') {
      errorToast('请输入地区价')
      return
    }
    showLoading('正在提交');
    const payload = {
      longitude: longitude.value,
      latitude: latitude.value,
      is_check: is_check.value ? 1 : 0,
      status: state1.value,
      type: state2.value,
      address: locName.value,
      price: JSON.stringify(price.value),
      name: name.value,
      admin_id: admin_id.value
    };
    toPublish('control/addTeam', payload, (obj : any) => {
      uni.hideLoading();
      const { code, msg } = obj;
      if (code === 1) {
        navBack()
      } else {
        errorToast(msg)
      }
    });
  }
  function changes(e : any, nums : string) {
    console.log(e.detail.data, nums, state1.value)
  }
</script>

<style scoped lang="less">
  .add {
    width: 480rpx;
    height: 100rpx;
    background: linear-gradient(-10deg, #2C96F9, #1B91FF);
    border-radius: 5px;
    text-align: center;
    line-height: 100rpx;
    color: #fff;
    margin: 40rpx auto 20rpx;
    font-size: 32rpx;
  }

  input {
    text-align: right;
  }

  .image {
    view {
      width: 92rpx;
      height: 92rpx;
      background: #ECF0F6;
      border-radius: 50%;
      text-align: center;
      line-height: 92rpx;
      font-size: 24rpx;
      margin: 10rpx;
    }

    .active {
      background: #2694FB;
      color: #fff;
    }
  }

  .top {
    margin-top: 10rpx;
  }

  .price view:nth-child(even) {
    width: 174rpx;
    height: 45rpx;
    border: 1px solid #CECECE;
    border-radius: 6rpx;
    text-align: center;
    line-height: 45rpx;
  }
</style>
<style>
  .space-between>>>.uni-data-checklist .checklist-group {
    justify-content: flex-end;
  }

  .space-between>>>.uni-data-checklist .checklist-group .checklist-box .checklist-content .checklist-text {
    color: #333 !important;
  }

  .space-between>>>.uni-data-checklist .checklist-group .checklist-box:nth-last-child(1) {
    margin-right: 0px;
  }
</style>